package com.joker.system.service;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.ObjectUtil;
import com.joker.common.constant.CacheConstants;
import com.joker.common.constant.Constants;
import com.joker.common.core.domain.event.LogininforEvent;
import com.joker.common.core.domain.entity.SysUser;
import com.joker.common.core.domain.model.RegisterBody;
import com.joker.common.enums.UserType;
import com.joker.common.exception.user.CaptchaException;
import com.joker.common.exception.user.CaptchaExpireException;
import com.joker.common.exception.user.UserException;
import com.joker.common.utils.MessageUtils;
import com.joker.common.utils.ServletUtils;
import com.joker.common.utils.StringUtils;
import com.joker.common.utils.redis.RedisUtils;
import com.joker.common.utils.spring.SpringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 注册校验方法
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysRegisterService {

    private final ISysUserService userService;

    /**
     * 注册
     */
    public Map<String, Object> register(RegisterBody registerBody) {

        SysUser sysUser = userService.selectUserByUserName(registerBody.getDeviceId());
        if (ObjectUtil.isNull(sysUser)) {

        }

        String username = registerBody.getUsername();
        String password = registerBody.getPassword();


        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(BCrypt.hashpw(password));
        sysUser.setUserType(UserType.APP_USER.getUserType());

        if (!userService.checkUserNameUnique(sysUser)) {
            throw new UserException("user.register.save.error", username);
        }

        Map<String, Object> map = new HashMap<>();
        // 邀请码为空,默认平台
        if (ObjectUtil.isEmpty(registerBody.getInviteCode())){
            map.put("superiorCode", "0");
        } else {
            // 邀请码未查询到代理默认先为1
            SysUser user = userService.selectUserByInviteCode(registerBody.getInviteCode());
            if (ObjectUtil.isEmpty(user)){
                map.put("superiorCode", "1");
                map.put("inviteCode", registerBody.getInviteCode());
            } else {
                map.put("superiorCode", "2");
                map.put("oneSuperiorCode", user.getUserId());
                SysUser twoUser = userService.selectUserById(Long.valueOf(user.getSuperiorAgent()));
                if (ObjectUtil.isNotEmpty(twoUser)){
                    map.put("twoSuperiorCode", twoUser.getUserId());

                    SysUser threeUser = userService.selectUserById(Long.valueOf(twoUser.getSuperiorAgent()));
                    if (ObjectUtil.isNotEmpty(threeUser)){
                        map.put("threeSuperiorCode", threeUser.getUserId());
                    }
                }
            }
        }

        long userId = userService.registerUser(sysUser);
        if (userId < 0) {
            throw new UserException("user.register.error");
        }
        recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success"));


        map.put("userId", userId);
        return map;
    }

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息内容
     * @return
     */
    private void recordLogininfor(String username, String status, String message) {
        LogininforEvent logininforEvent = new LogininforEvent();
        logininforEvent.setUsername(username);
        logininforEvent.setStatus(status);
        logininforEvent.setMessage(message);
        logininforEvent.setRequest(ServletUtils.getRequest());
        SpringUtils.context().publishEvent(logininforEvent);
    }

}
